package com.mcptt.db.loader.msg;

import java.util.List;
import java.util.Vector;

import com.cloudptt.api.product.log.Log;
import com.mcptt.db.DBProvider;
import com.mcptt.db.DbConst;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.db.model.UserInfo;

import android.annotation.TargetApi;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SessionListLoader implements LoaderManager.LoaderCallbacks<Cursor> 
{
//	private final static String THIS_FILE = "MsgListLoader";
	private Context ctx = null;
	private AddrInfo curUserInfo = null;
	private SessionListLoaderCb callback = null;
	public SessionListLoader(Context ctx,AddrInfo curUserInfo,SessionListLoaderCb callback)
	{
		this.ctx = ctx;
		this.curUserInfo = curUserInfo;
		this.callback = callback;
	}
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) 
	{
		if(curUserInfo == null)
		{
			return null;
		}
		String receiverNum = curUserInfo.getMcId();
		String selection = DbConst.COL_ReceiverNum + "=?";
		
		Log.debug(this.getClass(),"onCreateLoader selection = " + selection + " receiverNum = " + receiverNum);
		return new CursorLoader(this.ctx, DbConst.SESSION_URI, DBProvider.SESSION_FULL_PROJECTION,selection, new String[]{receiverNum},null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) 
	{
		if (data == null
				|| data.getCount() < 0)
		{
			return;
		}
		Log.debug(this.getClass(),"onLoadFinished Cursor.getCount() = " + data.getCount());
		List<SessionInfo> list = new Vector<SessionInfo>();
		Cursor cursor = data;
		while (cursor.moveToNext()) 
		{  
			SessionInfo info = new SessionInfo(cursor);  
			list.add(info);
		} 
		cursor.close();
		cursor = null;
		
		this.callback.onLoadFinished(list);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) 
	{
		this.callback.onLoaderReset();
	}
}
